// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Router from 'vue-router'

import {Message} from "element-ui";

import store from "../store";
import {isRelogin} from "../utils/request";
import { getToken } from '../utils/auth'

//后台
import AdminLogin from '../views/admin/Login'
import Main       from '../views/admin/Main'
import Welcome    from '../views/admin/Welcome'
import UserInfo   from '../views/admin/system/user'
import AuthRole   from '../views/admin/system/user/AuthRole.vue'
import Dept       from '../views/admin/system/Dept';
import EmpInfo    from '../views/admin/system/Empinfo'
import Role       from '../views/admin/system/Role'
import DictType   from '../views/admin/system/dict'
import DictData   from '../views/admin/system/dict/data'
import logininfor from "../views/admin/system/logininfor";
import operlog    from "../views/admin/system/operlog";

import Area       from '../views/admin/work/Area'
import Spot       from '../views/admin/work/Spot'
import Order      from '../views/admin/work/Order'

import Log        from '../views/admin/monitor/Log'
import Echarts    from '../views/admin/monitor/Echarts'
import Server     from '../views/admin/monitor/Server'
import Druid      from '../views/admin/monitor/Druid'


// 用户端
import HomePage   from '../views/forward/HomePage'
import Userlogin  from '../views/forward/UserLogin'
import Goods      from '../views/forward/Goods'
import Cart       from '../views/forward/Cart'
import User       from '../views/forward/User'


Vue.use(Router)

const whiteList = ['/login', '/auth-redirect', '/bind', '/register','/']

/**
 * Note: 路由配置项
 *
 * hidden: true                     // 当设置 true 的时候该路由不会再侧边栏出现 如401，login等页面，或者如一些编辑页面/edit/1
 * alwaysShow: true                 // 当你一个路由下面的 children 声明的路由大于1个时，自动会变成嵌套的模式--如组件页面
 *                                  // 只有一个时，会将那个子路由当做根路由显示在侧边栏--如引导页面
 *                                  // 若你想不管路由下面的 children 声明的个数都显示你的根路由
 *                                  // 你可以设置 alwaysShow: true，这样它就会忽略之前定义的规则，一直显示根路由
 * redirect: noRedirect             // 当设置 noRedirect 的时候该路由在面包屑导航中不可被点击
 * name:'router-name'               // 设定路由的名字，一定要填写不然使用<keep-alive>时会出现各种问题
 * query: '{"id": 1, "name": "ry"}' // 访问路由的默认传递参数
 * roles: ['admin', 'common']       // 访问路由的角色权限
 * permissions: ['a:a:a', 'b:b:b']  // 访问路由的菜单权限
 * meta : {
    noCache: true                   // 如果设置为true，则不会被 <keep-alive> 缓存(默认 false)
    title: 'title'                  // 设置该路由在侧边栏和面包屑中展示的名字
    icon: 'svg-name'                // 设置该路由的图标，对应路径src/assets/icons/svg
    breadcrumb: false               // 如果设置为false，则不会在breadcrumb面包屑中显示
    activeMenu: '/system/user'      // 当路由设置了该属性，则会高亮相对应的侧边栏。
  }
 */

//创建一个路由
const routes = [
  { path: '/', name: '登录页', component: AdminLogin,meta:{title:"登录页"}},
  { path: '/main', name:'首页', component: Main,
    children: [
      { path:'/', component: Welcome, name:'欢迎页',
        meta: {
          title: '首页',
            icon: 'dashboard',
            affix: true
        }
      },
      { path:'/system/user',
        component: UserInfo,
        name:'用户管理' ,
        meta: {
          title: '用户管理',
          activeMenu: '/system/dict'
        }
      },
      { path:'/system/user-auth/role',
      component: AuthRole,
      name:'分配角色' ,
      meta: {
        title: '分配角色',
        activeMenu: '/system/user'
      }
      },
      {
        path: '/system/dept',
        component: Dept,
        name: '部门管理',
        meta: {
          title: '部门管理',
          activeMenu: '/system/dict',
          icon: 'dashboard',
        }
      },
      { path: '/system/empinfo',
        component: EmpInfo,
        name:'员工管理' ,
        meta: {
          title: '员工管理',
          activeMenu: '/system/dict'
        }
      },
      { path: '/system/role',
        component: Role,
        name:'角色管理',
        meta: {
          title: '角色管理',
          activeMenu: '/system/dict'
        }
      },
      { path: '/system/dict',
        component: DictType,
        name:'字典管理' ,
        meta: {
          title: '字典管理',
          activeMenu: '/system/dict'
        }
      },
      { path: '/system/log/logininfor',
        component: logininfor,
        name:'登录日志' ,
        meta: {
          title: '登录日志',
          activeMenu: '/system/log'
        }
      },
      { path: '/system/log/operlog',
        component: operlog,
        name:'操作日志' ,
        meta: {
          title: '操作日志',
          activeMenu: '/system/log'
        }
      },
      { path: '/system/dict-data', component: DictData,name:'字典详情' ,meta: { title: '字典详情', activeMenu: '/system/dict' }},
      { path: '/work/area', component: Area ,name:'首页' },
      { path: '/work/spot', component: Spot ,name:'首页' },
      { path: '/work/order', component: Order ,name:'首页' },
      { path: '/monitor/log', component: Log ,name:'首页' },
      { path: '/monitor/echarts', component: Echarts,name:'首页'  },
      { path: '/monitor/server', component:Server ,name:'首页' },
      { path: '/monitor/druid', component:Druid ,name:'首页' },
    ]
  },
  { path: '/user/auth', component: Userlogin ,
    children:[
      {path:'/', component: HomePage},
      { path: 'user/cart', component: Cart },
      { path: '/user', component: User },
      {path:'/first', component: HomePage},
      { path: '/user/goods', component: Goods },
    ]
  }

]

//创建一个路由对象，命名为router
const router = new Router({
  //使用路由数组初始化路由
  routes: routes,
  // 去掉url中的#
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
})

// 防止连续点击多次路由报错
let routerPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}

/*router.beforeEach((to, from, next) => {
  console.log(to.name+" "+to.path);
  if (to.path === '/' || to.path === 'regist') {
    //对登录页和注册页放行
    next();
    console.log("路由守卫白名单放行");
  } if (!getToken()) {
    //去登录
    next('/');
    console.log("路由守卫触发拦截");
  } else {
    //继续路由
    next();
    console.log("路由守卫触发继续");
  }
})*/

router.beforeEach((to, from, next) => {
  //NProgress.start()
  //根据路由变化修改标题名称
  to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
  if (getToken()) {
    /* 有权限 */
    if (to.path === '/login') {
      next({ path: '/' })
      //NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('user/GetInfo').then(() => {
          isRelogin.show = false
          // store.dispatch('GenerateRoutes').then(accessRoutes => {
          //   // 根据roles权限生成可访问的路由表
          //   router.addRoutes(accessRoutes) // 动态添加可访问路由表
          //   next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          // })
          next();
        }).catch(err => {
          store.dispatch('user/LogOut').then(() => {
            Message.error(err)
            next({ path: '/' })
          })
        })
      } else {
        console.log("路由守卫触发继续");
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      console.log("路由守卫白名单放行");
      next()
    } else {
      console.log("路由守卫触发拦截");
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      //NProgress.done()
    }
  }
})

router.afterEach(() => {
  //NProgress.done()
})


//暴露路由对象
export default router
